package tech.konata.packetfix.mixins;

import com.viaversion.viaversion.api.protocol.version.ProtocolVersion;
import de.florianmichael.vialoadingbase.ViaLoadingBase;
import net.minecraft.item.ItemStack;
import net.minecraft.network.PacketBuffer;
import net.minecraft.network.play.client.C08PacketPlayerBlockPlacement;
import net.minecraft.util.BlockPos;
import org.spongepowered.asm.mixin.Mixin;
import org.spongepowered.asm.mixin.Overwrite;
import org.spongepowered.asm.mixin.Shadow;
import tech.konata.packetfix.PluginMain;

import java.io.IOException;

@Mixin(C08PacketPlayerBlockPlacement.class)
public class MixinC08 {

    @Shadow
    private BlockPos position;
    @Shadow
    private int placedBlockDirection;
    @Shadow
    private ItemStack stack;
    @Shadow
    private float facingX;
    @Shadow
    private float facingY;
    @Shadow
    private float facingZ;

    @Overwrite
    public void readPacketData(PacketBuffer buf) throws IOException
    {
        this.position = buf.readBlockPos();
        this.placedBlockDirection = buf.readUnsignedByte();
        this.stack = buf.readItemStackFromBuffer();
        if (ViaLoadingBase.getInstance().getTargetVersion().newerThanOrEqualTo(ProtocolVersion.v1_12_2) && PluginMain.packetFix.isEnabled()) {
            this.facingX = (float)buf.readUnsignedByte();
            this.facingY = (float)buf.readUnsignedByte();
            this.facingZ = (float)buf.readUnsignedByte();
        } else {
            this.facingX = (float)buf.readUnsignedByte() / 16.0F;
            this.facingY = (float)buf.readUnsignedByte() / 16.0F;
            this.facingZ = (float)buf.readUnsignedByte() / 16.0F;
        }
    }

    @Overwrite()
    public void writePacketData(PacketBuffer p_writePacketData_1_) throws IOException{
        p_writePacketData_1_.writeBlockPos(this.position);
        p_writePacketData_1_.writeByte(this.placedBlockDirection);
        p_writePacketData_1_.writeItemStackToBuffer(this.stack);

        if (ViaLoadingBase.getInstance().getTargetVersion().newerThanOrEqualTo(ProtocolVersion.v1_12_2) && PluginMain.packetFix.isEnabled()) {
            p_writePacketData_1_.writeByte((int)(this.facingX));
            p_writePacketData_1_.writeByte((int)(this.facingY));
            p_writePacketData_1_.writeByte((int)(this.facingZ));
        } else {
            p_writePacketData_1_.writeByte((int)(this.facingX * 16.0F));
            p_writePacketData_1_.writeByte((int)(this.facingY * 16.0F));
            p_writePacketData_1_.writeByte((int)(this.facingZ * 16.0F));
        }
    }

}
